package com.gxa.employment.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @Description: jwt令牌，权限校验
 * @Author:
 * @DateTime: 2025/3/6 14:26
 **/
public class JwtUtil {
   private static final Integer EXPIRED_TIME = 24*2*30*60*1000;
   private static final String SECRET_KEY = "gxa123#";

    /**
     * 生成jwt令牌
     * @param claims
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String generate(Map<String, String> claims) throws UnsupportedEncodingException {
        //生成jwt构建器
        JWTCreator.Builder builder = JWT.create();
        //添加载荷  (k, v) -> builder.withClaim(k, v)
        claims.forEach(builder::withClaim);
        //添加过期时间
        builder.withExpiresAt(new Date(System.currentTimeMillis()+EXPIRED_TIME));
        //生成签名
        return builder.sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 解析jwt领取的载荷信息
     * @param token
     * @return
     */
    public static String getClaim(String token,String key) throws UnsupportedEncodingException {
        //解析载荷数据
        DecodedJWT decode = JWT.decode(token);
        Map<String, Claim> claims = decode.getClaims();
        //获取值
        return claims.get(key).asString();
    }

    /**
     * 判断是否过期
     * @param token
     * @return
     */
    public static Boolean isExpire(String token) {
        DecodedJWT decode = JWT.decode(token);
        Date expiresAt = decode.getExpiresAt();
        return expiresAt.before(new Date());
    }

    /**
     * 校验jwt令牌是否合法
     * @param token
     * @throws UnsupportedEncodingException
     */
    public static void verify(String token) throws UnsupportedEncodingException {
        //获取秘钥信息
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        //获取校验对象
        Verification require = JWT.require(algorithm);
        //进行校验
        require.build().verify(token);
    }
}
